import os
import re
import MySQLdb
import requests
from bs4 import BeautifulSoup

baseUrl = 'http://fundf10.eastmoney.com/jbgk_$FUNDID$.html'
fundUrl = ''

def baseMsg(fundId):
    fundUrl = baseUrl.replace("$FUNDID$", fundId)
    # print(fundUrl)
    getJBGK(fundId, fundUrl)

# 读取基金基本信息
def getJBGK(fundId, fundUrl):
    header = {
        'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        'Referer' : fundUrl
    }
    resp = requests.get(fundUrl, headers=header)
    Soup = BeautifulSoup(resp.text, 'html.parser')
    div = Soup.find("div", class_="bs_gl")
    
    if not div is None:
        i = 1
        # birthday,curManager,scale,company
        labels = div.select("label")
        for label in div.select("label"):
            print("Num: %s Contont: %s" % (i, label.text.replace(" ","").replace("\r\n","")))
            i += 1
        # birthday = labels[0].text.replace(" ","").replace("\r\n",""))
        birthday = labels[0].text.replace(" ","").replace("\r\n","").split("：")[1]
        curManager = labels[1].text.replace(" ","").replace(" ","").replace("\r\n","").split("：")[1]
        scale = labels[4].text.replace(",", "").replace("亿元", "").replace(" ","").replace(" ","").replace("\r\n","").split("：")[1].split("（")[0]
        company = labels[3].text.replace(" ","").replace(" ","").replace("\r\n","").split("：")[1]

        # 准备更新信息
        if (birthday == "---"):
            birthday = None
        if (scale == "---"):
            scale = None

        updateBaseInfo(fundId, birthday, curManager, company, scale)

    else:
        print("格式不对的基金：%s" % fundId)



def updateBaseInfo(fundId, birthday, curManager, company, scale):
    db = MySQLdb.connect("localhost", "jijin", "jijin", "jijin", charset='utf8' )

    cursor = db.cursor()

    try:
        par = (birthday, scale, curManager, company, fundId)
        cursor.execute("UPDATE fund SET birthday=%s, scale=%s, curManager=%s, company=%s WHERE fundId=%s", par)
        db.commit()
    except Exception as ex:
        print("出现如下异常%s"%ex)
        print(ex)

    db.close()
